package com.leyou.upload.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

// 定义配置类,并且注册CorsFilter
@Configuration
public class LeyouCorsConfiguration {
    // 方法注入容器里
    @Bean
    public CorsFilter corsFilter() {
        // 1.初始化cors配置对象
        CorsConfiguration config = new CorsConfiguration();
        //2.设置允许的跨域的域名,如果要携带cookie，就不要写*，*代表所有域名都支持，否则cookie就无法使用了
        config.addAllowedOrigin("http://manage.leyou.com");
        //3.允许携带cookie
        config.setAllowCredentials(true);
        //4.允许请求方式
        config.addAllowedMethod("*");  // 允许所有的请求方法
        config.addAllowedHeader("*");  // 允许携带任何请求头信息
        //config.addAllowedMethod("OPTIONS"); // 也可以单独设置
        //config.addAllowedMethod("HEAD");
        //config.addAllowedMethod("GET");
        //config.addAllowedMethod("PUT");
        //config.addAllowedMethod("POST");
        //config.addAllowedMethod("DELETE");
        //config.addAllowedMethod("PATCH");

        // 5.初始化cors配置源对象
        UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource();
        configurationSource.registerCorsConfiguration("/**",config);

        //7.返回新的corsFilter
        return new CorsFilter(configurationSource);
    }
}
